package com.bootdo.app.common.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @auther: 作者: Along
 * @description: 图片工具类
 * @Date: created in 2019/12/19 11:17
 */
public class ImageUtil {

    public static final int WIDTH = 1200;

    public static final int HEIGHT = 1000;

    public static boolean saveMini(InputStream imgSrc, String destImgPath, String imgFormatName){
        // 读取原始图片
        try {
            final BufferedImage read = ImageIO.read(imgSrc);
            read.flush();
            int height = read.getHeight()/2;
            int width = read.getWidth()/2;
            // 获取缩略图
            final Image scaledInstance = read.getScaledInstance(width, height, Image.SCALE_SMOOTH);//选择一种比缩放速度更高的图像平滑度的图像缩放算法。
//            final Image scaledInstance = read.getScaledInstance(width, height, Image.SCALE_FAST);//选择一个图像缩放算法，给出了更高的优先级缩放速度比缩放图像的平滑。
//            final Image scaledInstance = read.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);//使用面积平均图像缩放算法

            // 创建一个新的BufferedImage对象
            BufferedImage newImage = new BufferedImage(width,height,read.getType());
            // 获取新画笔
            final Graphics graphics = newImage.getGraphics();
            // 绘制缩略图
            graphics.drawImage(scaledInstance,0,0,null);
            graphics.dispose();// 释放资源
            // 保存绘制出来的缩略图
            File file = new File(destImgPath);
            if(!file.exists()){
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            return ImageIO.write(newImage, imgFormatName, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    public static void main(String[] args)  {

        String imgSrc="E:/aa/a.jpg";
		String destImgPath="E:/aa/ImgIo/a_mini_final.jpg";
        boolean testLessenImg = false;
        try {
            testLessenImg = saveMini(new FileInputStream(imgSrc), destImgPath,  "jpg");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if(testLessenImg){
			System.out.println("图片生成成功");
		}else{
			System.out.println("图片生成失败");
		}

    }
}
